﻿using System;
using System.Linq;
using System.Net;
using System.Net.Mime;

namespace TathamOddie.OpenSearchValidator.Logic.Tasks
{
	class DownloadHelper
	{
        public static WebResource Download(IWebLoader webLoader, ValidationTaskResult result, string resourceName, bool resourceNameIsPlural, Uri address, string expectedMediaType)
        {
            return Download(webLoader, result, resourceName, resourceNameIsPlural, address, new[] {expectedMediaType});
        }

		public static WebResource Download(IWebLoader webLoader, ValidationTaskResult result, string resourceName, bool resourceNameIsPlural, Uri address, string[] expectedMediaTypes)
		{
			var pastTenseIndicative = resourceNameIsPlural ? "were" : "was";

			var resource = webLoader.Download(address);

			if (resource == null)
			{
				result.AddMessage(MessageType.Failure, "Failed to download {0} from [{1}].", resourceName, address);
				return null;
			}
		    if (resource.StatusCode != HttpStatusCode.OK)
		    {
		        result.AddMessage(MessageType.Failure, "Failed to download {0} from [{1}]. HTTP status code was [{2}].", resourceName, address, (int)resource.StatusCode);
		        return null;
		    }
		    
            var actualMediaType = new ContentType(resource.ContentType).MediaType;
		    if (!expectedMediaTypes.Contains(actualMediaType, StringComparer.Ordinal))
		    {
		        result.AddMessage(
                    MessageType.Warning,
                    "The {0} at [{1}] {2} served with media type of [{3}] but [{4}] was expected.",
                    resourceName,
                    address,
                    pastTenseIndicative,
                    actualMediaType,
                    string.Join(" or ", expectedMediaTypes));
		    }

		    result.AddMessage(MessageType.Success, "Downloaded {0} from [{1}].", resourceName, address);

		    return resource;
		}
	}
}